"use strict";
var stage;
var curFigureId, blessingId;

var activity = (function() {
    var spriteStore;
    var goffseY = 0, gheightpx = 0;

    var figureOrder = [1,2,3,4,5];

    var activeSprite = {
        image: null,
        back    : {width:109, height:160, x: 747, y:  2},
        blessing: {width:624, height: 63, x:   2, y:  2},
        btngoto : {width:346, height:120, x: 516, y:164},
        btnstart: {width:512, height:152, x:   2, y:221},
        btnstop : {width:512, height:152, x:   2, y: 67},
        refresh : {width:117, height:160, x: 628, y:  2}
    };


    var activity = {

        init: function() {
            var gheight = $(window).height();
            gheightpx = px2rem(gheight) * 100;
            var canvas = document.getElementById('canvas');
            canvas.style.width = "7.5rem";
            canvas.style.height = gheightpx/100 + "rem";
            canvas.width = 750;
            canvas.height = gheightpx;
            stage = this.stage = new createjs.Stage(canvas);
            createjs.Touch.enable(stage);

            createjs.Ticker.addEventListener("tick", function(e) {
                dragonBones.WorldClock.clock.advanceTime(e.delta * 0.001);
                stage.update();
            });

            activity.initLoadding();
        },

        initLoadding: function() {
            var self = this;
            var loadCont = self.loadCont =  new createjs.Container();
            loadCont.width = stage.width;
            loadCont.height = stage.height;
            var loadBg = self.loadBg = new createjs.Bitmap(utils.getRes("load1_bg"));
            
            self.loadCont.y = (gheightpx - 1624)/2;
            self.loadBg.y = -self.loadCont.y + (gheightpx-1624);

            var skipIcon = self.skipIcon = new createjs.Bitmap(utils.getRes("skip_png"));
            skipIcon.x = 646;
            skipIcon.y = 15-loadCont.y;
            
            var skipBtn = self.skipBtn = new createjs.Shape();
            skipBtn.graphics.beginFill("#ffffff").drawRect(0,0,180,160);
            skipBtn.x = 750-180;
            skipBtn.alpha = 0.01;

            skipBtn.visible = skipIcon.visible = false;

            loadCont.addChild(loadBg, skipIcon);
            stage.addChild(skipBtn);

            stage.addChildAt(loadCont, 0);
            
            self._loaddingStep = 1;
            utils.loadSkeleton("images/wx/activity/godwealth/load_st1", "load_st1", function(textureImage, textureData, skeletonData) {
                var armature = self.loadSt1Armature = self.createArmature(textureImage, textureData, skeletonData);
                self.loadCont.addChild(armature.display);
                armature.display.x = 375;
                armature.display.y = 1334/2 -self.loadCont.y;
                armature.animation.gotoAndPlay("newAnimation", -1, -1, 1);
                armature.once(dragonBones.AnimationEvent.COMPLETE, function(e){
                    if (self._loaddingStep==1) { 
                        self.goonIcon.visible = self.goonBtn.visible = true;
                    }
                }, armature);
            });

            var goonIcon = self.goonIcon = new createjs.Bitmap(utils.getRes("goon_png"));
            goonIcon.x = (750-153)/2;
            goonIcon.y = (gheightpx-86);

            var goonBtn = self.goonBtn = new createjs.Shape();
            goonBtn.graphics.beginFill("#ffffff").drawRect(0,0,750,460);
            goonBtn.x = 0;
            goonBtn.y = (gheightpx-460);
            goonBtn.alpha = 0.01;
            self.goonIcon.visible = self.goonBtn.visible = false;
            stage.addChild(goonIcon, goonBtn);


            skipBtn.on("click", function() {
                self.readyActivity();
            });

            goonBtn.on("click", function() {
                self._loaddingNext();
            });

            loadBg.on("click", function() {
                if (self._loaddingStep==1) {
                    self.loadSt1Armature.animation.stop();
                    self.loadSt1Armature.animation.gotoAndPlay("newAnimation_1", -1, -1, 1);
                    self.goonIcon.visible = self.goonBtn.visible = true;
                } else if (self._loaddingStep==2) {
                    self.loadSt2Armature.animation.gotoAndPlay("newAnimation_1", -1, -1, 1);
                    self.goonIcon.visible = self.goonBtn.visible = true;
                }
            });

        },

        _loaddingNext: function() {
            var self = activity;
            clearTimeout(self._loaddingNextTimer);
            if (!activity.load_st2_isReady) return;
            var loadBg = self.loadBg;
            if (++self._loaddingStep==2) {
                self.goonIcon.visible = self.goonBtn.visible = false;
                loadBg.image = utils.getRes("load2_bg");
                self.loadBg.y = -self.loadCont.y +  Math.min(self.loadCont.y, (gheightpx-1624)/2 - 38 );
                self.skipIcon.y = 15-self.loadCont.y;

                self.loadCont.removeChild(self.loadSt1Armature.display);
                utils.loadSkeleton("images/wx/activity/godwealth/load_st2", "load_st2", function(textureImage, textureData, skeletonData) {
                    var armature = self.loadSt2Armature = self.createArmature(textureImage, textureData, skeletonData);
                    self.loadCont.addChild(armature.display);
                    armature.display.x = 375;
                    armature.display.y = 1334/2 -self.loadCont.y;
                    armature.animation.gotoAndPlay("newAnimation", -1, -1, 1);
                    armature.once(dragonBones.AnimationEvent.COMPLETE, function(e){
                        if (self._loaddingStep==2) { 
                            self.goonIcon.visible = self.goonBtn.visible = true;
                        }
                    }, armature);
                });
            } else {
                self.loadCont.removeChild(self.loadSt2Armature.display);
                self.loadBg.off("click", self._loaddingNext);
                self.readyActivity();
            }
        },

        readyActivity: function() {
            var self = activity;
            if (self.intedActed) return;
            self.intedActed = true;
            createjs.Tween.get(self.loadCont, { override: true }).to({ alpha: 0 }, 150).call(function () {
                stage.removeAllChildren();
                self.initActivity();
            });
            
        },

        initActivity: function() {
            var self = this;
            
            activeSprite.image = utils.getRes("sprite_png");

            var activitBg = new createjs.Bitmap(utils.getRes("activity_jpg"));
            activitBg.y = (gheightpx - 1448)/2;
            stage.addChildAt(activitBg, 0);

            var btnBack    = self.btnBack = self.createSprite("back", activeSprite);
            var btnRefresh = self.btnRefresh = self.createSprite("refresh", activeSprite);
            btnBack.x = 5;
            btnRefresh.x = 750 - 112;
            btnBack.visible = false;
            btnRefresh.visible = false;
            stage.addChild(btnBack, btnRefresh);

            self.decoratorBtn(btnBack);
            self.decoratorBtn(btnRefresh);
            
            $("#Container").addClass("loaded");
            self.renderStartPage();

            utils.loadSkeleton("images/wx/activity/godwealth/weicaishen", "weicaishen", function(textureImage, textureData, skeletonData) {
                var greateArmature = self.greateArmature = self.createArmature(textureImage, textureData, skeletonData);
                stage.addChildAt(greateArmature.display, 1);
                greateArmature.display.visible = false;
                greateArmature.display.x = 375;
                greateArmature.display.y = 1334/2 + Math.min(0, (gheightpx-1334));

                utils.loadRes([
                    { url: utils.path("images/wx/activity/godwealth/switch_tex.png"),  type: "image", name: "switch_tex_png"  },
                ], function() {

                });

                setTimeout(function() {
                    var btnArmature = self.btnArmature;
                    greateArmature.once(dragonBones.AnimationEvent.COMPLETE, function(e){
                        greateArmature.animation.gotoAndPlay("stay", -1, -1, 0);
                        self.bindEvent();
                    }, greateArmature);
                    greateArmature.display.visible = true;
                    greateArmature.animation.gotoAndPlay("onsite", -1, -1, 1);
                }, 0);
                
            });
        },

        bindEvent: function() {
            var self = this;
            var btnArmature = self.btnArmature;
            var btnPlay = new createjs.Shape();
            btnPlay.x = 375-215.5;
            btnPlay.y = 1080 + (gheightpx-1206) - 70;
            btnPlay.graphics.beginFill("#ffffff").drawRect(0,0,431,140);
            btnPlay.alpha = 0.01;
            stage.addChildAt(btnPlay, stage.numChildren);
            var clicked = false;

            btnPlay.on("click", function(event) {
                if (clicked) return;
                clicked = true;
                setTimeout(function() {
                    clicked = false;
                }, 2000);
                var greateArmature = self.greateArmature;
                var chooseArmature = self.chooseArmature;
                btnArmature.animation.stop();
                if (self.btnStatus!==1) { // 点击开始
                    btnArmature.animation.stop();
                    createjs.Tween.get(btnArmature.display, { override: true })
                        .to({ alpha: 0.1 }, 200).call(function () {
                            btnArmature.display.visible = false;
                        });
                    setTimeout(function() {
                        self.btnRefresh.visible = true;
                        self.btnBack.visible = true;
                        greateArmature.animation.gotoAndPlay("stayplay", -1, -1, 0);
                        self.addChooser();
                        self.btnStatus = 1;
                        setTimeout(function() {
                            btnArmature.display.visible = true;
                            btnArmature.animation.gotoAndStop("点击选择", 0, 0, 0);
                            createjs.Tween.get(btnArmature.display, { override: true })
                                .to({ alpha: 1.0 }, 200).call(function () {
                                    btnArmature.animation.gotoAndPlay("点击选择", -1, -1, 0);
                                });
                        }, 0);
                    }, 1500);
                    greateArmature.animation.gotoAndPlay("offsite", -1, -1, 1);
                } else { // 点击选择
                    var randNum = utils.randomNum(4);
                    curFigureId = figureOrder[randNum];
                    var askes = blessData[curFigureId].ask;
                    var t = utils.randomNum(askes.length-1);
                    blessingId = ''+curFigureId + (t+1);

                    chooseArmature.animation.gotoAndStop("newAnimation", 0, randNum * 0.2);
                    $(".blessing-desc").attr("src", utils.path('images/wx/activity/godwealth/blessing/'+blessingId+'.png'));
                    var fimage = new Image();
                    fimage.src = utils.path('images/wx/activity/godwealth/avartFigure/'+curFigureId+'2.png');
                    
                    setTimeout(function() {
                        self.btnStatus = 0;
                        btnArmature.animation.stop();
                        btnArmature.display.visible = false;
                        chooseArmature.display.visible = false;
                        self.showBlessingPop();
                    }, 500);
                }
            });

            self.btnBack.handleClick = function() {
                if (self.btnStatus==1) {
                    self.btnRefresh.visible = false;
                    self.btnBack.visible = false;

                    var btnArmature = self.btnArmature;
                    var greateArmature = self.greateArmature;
                    btnArmature.display.visible = true;
                    self.btnStatus = 0;
                    btnArmature.animation.gotoAndPlay("开始祈福", -1, -1, 0);

                    if (self.chooseArmature) {
                        self.chooseArmature.animation.stop();
                        self.chooseArmature.display.visible = false;
                    }

                    greateArmature.once(dragonBones.AnimationEvent.COMPLETE, function(e){
                        greateArmature.animation.gotoAndPlay("stay", -1, -1, 0);
                    }, greateArmature);
                    greateArmature.display.visible = true;
                    greateArmature.animation.gotoAndPlay("onsite", -1, -1, 1);
                } else {
                    if (typeof WeixinJSBridge !== "undefined") {
                        WeixinJSBridge.invoke("closeWindow", {}, function() {

                        });
                    } else {
                        history.go(-1);
                    }
                }
            };

            self.btnRefresh.handleClick = function() {
                location.reload();
            };

        },

        createArmature: function(textureImage, textureData, skeletonData) {
            var dragonbonesFactory = this.dragonbonesFactory = new dragonBones.CreatejsFactory();
            dragonbonesFactory.addTextureAtlas(new dragonBones.TextureAtlas(textureImage, textureData));
            dragonbonesFactory.addDragonBonesData(dragonBones.DataParser.parseDragonBonesData(skeletonData));
            var armature = dragonbonesFactory.buildArmature(skeletonData.armature[0].name);
            dragonBones.WorldClock.clock.add(armature);
            return armature;
        },

        createSprite: function(name, spriteStore, props) {
            var self = this;
            var el = new createjs.Bitmap(spriteStore.image);
            el.sourceRect = spriteStore[name];
            return el;
        },

        decoratorBtn: function(spriteEl) {
            var x = spriteEl.x, y = spriteEl.y;
            var bounds = spriteEl.getBounds();
            spriteEl.regX = bounds.width >> 1;
            spriteEl.regY = bounds.height >> 1;
            spriteEl.x += spriteEl.regX;
            spriteEl.y += spriteEl.regY;
            spriteEl.on("click", function() {
                createjs.Tween.get(spriteEl, { override: true })
                    .to({ scaleX: 0.9, scaleY: 0.9 }, 100).call(function () {
                        if (typeof spriteEl.handleClick === "function") spriteEl.handleClick();
                    }).to({ scaleX: 1.0, scaleY: 1.0 }, 200, createjs.Ease.backOut);
            });
        },

        renderStartPage: function() {
            var self = this;
            utils.loadSkeleton("images/wx/activity/godwealth/btnplay", "btnplay", function(textureImage, textureData, skeletonData) {
                var armature  = self.btnArmature = self.createArmature(textureImage, textureData, skeletonData);
                stage.addChild(armature.display);
                armature.display.x = 375;
                armature.display.y = 1084 + (gheightpx-1206);
                // armature.display.visible = false;
                armature.animation.gotoAndPlay("开始祈福", -1, -1, 0);
            });
        },

        addChooser: function() {
            var self = this;
            if (!self.initedChooser) {
                utils.loadSkeleton("images/wx/activity/godwealth/switch", "switch", function(textureImage, textureData, skeletonData) {
                    self.initedChooser = true;
                    var armature = self.chooseArmature = self.createArmature(textureImage, textureData, skeletonData);
                    stage.addChildAt(armature.display, 2);
                    armature.display.x = 375;
                    armature.display.y = 1206/2 + (gheightpx-1206) + 60 + 20;
                    setTimeout(function() {
                        armature.animation.gotoAndPlay("newAnimation", -1, -1, 0);
                    }, 650);
                });
            } else {
                self.chooseArmature.display.visible = true;
                setTimeout(function() {
                    self.chooseArmature.animation.gotoAndPlay("newAnimation", -1, -1, 0);
                }, 650);
            }
        },

        showBlessingPop: function() {
            var self = this;
            var $maskLayer = $('<div class="maskLayer"></div>');
            $('#Container').append($maskLayer);
            var subTextureData = utils.getRes("switch_tex_json")["SubTexture"];
            var frameData = subTextureData.find(function(item) {
                return item.name == curFigureId;
            });
            
            $(".figure-bitmap").css({ 
                'width': '6.58rem', 'height': '7.19rem',
                'left': (750-678)/200 + 'rem',
                'top': (811-719)/100 + 'rem'
            }).attr('src', utils.path('images/wx/activity/godwealth/avartFigure/'+curFigureId+'2.png'));
            $('.popup, .maskLayer').addClass('showed');
        }

    };

    return activity;
})();